package eip.chapter8.expiration.impl;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.soap.SOAPEnvelope;
import org.apache.axis2.AxisFault;
import org.apache.axis2.client.Options;
import org.apache.axis2.context.MessageContext;
import org.apache.axis2.context.OperationContext;
import org.apache.axis2.context.ServiceContext;
import org.apache.axis2.wsdl.WSDLConstants;
import org.apache.savan.SavanException;
import org.apache.savan.publication.client.PublicationClient;
import org.apache.savan.storage.SubscriberStore;
import org.apache.savan.util.CommonUtil;

public class RestaurantInquiryMediatorService {

	/** the action to invoke on the registered clients */
	private final String PUB_ACTION = "urn:processInquiry";
	
	/** Axis2's service context, used for sending the updates */
	private ServiceContext serviceContext = null;

	private MessageContext msgCtx;
	
	/**
	 * Default constructor
	 */
	public RestaurantInquiryMediatorService() {
	}
	
	/**
	 * Injected by Axis2
	 * 
	 * @param opCtx
	 * @throws AxisFault
	 */
	public void setOperationContext(OperationContext opCtx) throws AxisFault {
        msgCtx = opCtx.getMessageContext(
           WSDLConstants.MESSAGE_LABEL_IN_VALUE);
  }
	
	/**
	 * We implement this 'lifecycle' method to make sure we get a reference
	 * to the serviceContext
	 * 
	 * @param serviceContext
	 * @throws AxisFault
	 */
	public void init(ServiceContext serviceContext) throws AxisFault {
		this.serviceContext = serviceContext;
	}

	/**
	 * The soap method that can be called to send updates to the registered
	 * listeners.
	 * 
	 * @throws SavanException 
	 */
	public void sendInquiry(OMElement input) throws SavanException {
		SOAPEnvelope envelopeOld = (SOAPEnvelope) ((OMElement)input.getParent()).getParent();
		sendToSubscribers(envelopeOld);
	}

	/**
	 * Send a list of updates to the registered listeners 
	 * 
	 * @param updates
	 * @throws SavanException 
	 */
	private void sendToSubscribers(SOAPEnvelope message) throws SavanException  {
		SubscriberStore store = (SubscriberStore) CommonUtil
				.getSubscriberStore(serviceContext.getAxisService());
		Options options = new Options();
		options.setAction(PUB_ACTION);
		options.setReplyTo(msgCtx.getReplyTo());
		PublicationClient.sendPublication(message, serviceContext
				.getConfigurationContext(), options, store);
	}
}
